import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/pages/teacher/coreMaterialBooksTab.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerTeacher.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import '../../themes/pageStyles.dart';
import '../../themes/appTheme.dart';
import '../../widgets/sidebars/teacherSidebar.dart';
import 'package:ichinesereader/models/class/ClassDetailsNew.dart';

class CoreMaterialBooksForTeacherPage extends StatefulWidget {
  static const String routeName = '/teacher/corematerials';

  @override
  State<CoreMaterialBooksForTeacherPage> createState() =>
      _CoreMaterialBooksForTeacherPageState();
}

class _CoreMaterialBooksForTeacherPageState
    extends State<CoreMaterialBooksForTeacherPage>
    with SingleTickerProviderStateMixin {
  final box = Hive.box('appconfig');
  final BooksController _booksController = Get.find();
  final SchoolAdminController _schoolAdminController = Get.find();
  bool isTeacher = false;
  List<Tree> _subPrograms = [];
  late TabController coreMaterialTabController;
  List<String> tabNames = [];

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    String? _programId =
        box.get(CacheManagerKey['currentclassProgramId'].toString());
    var programs = _schoolAdminController
        .currentClassPrograms.value.tree!.lowerProgram as List<Tree>;

    if (programs.isNotEmpty && _programId != null) {
      _subPrograms =
          programs.where((element) => element.id == _programId).toList();
    }

    if (isTeacher) {
      _booksController.fetchBookAllFolders();

      if (_subPrograms.length > 0) {
        _subPrograms[0].lowerProgram!.forEach((element) {
          tabNames.add(element.name.toString());
        });
      }
      coreMaterialTabController =
          TabController(vsync: this, length: tabNames.length);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build TextBookForTeacherPage');
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.teacherPageItems.indexWhere((page) =>
        page.route == '/teacher/themedbooks' ||
        page.route == '/teacher/corematerials');
    final PageStyles _pageStyles = PageStyles();

    return tabNames.length > 0
        ? DefaultTabController(
            length: tabNames.length,
            child: Scaffold(
              appBar: isSmallScreen
                  ? CustomAppBar(title: 'Core Materials'.tr)
                  : null,
              drawer: isSmallScreen ? TeacherAppDrawer() : null,
              body: Container(
                decoration: _pageStyles.pageBoxDecoration(),
                child: Row(
                  children: [
                    Visibility(
                        visible: !isSmallScreen,
                        child: TeacherSidebarX(
                          selectedIndex: _selectedSidebarItem,
                          isBigScreen: isBigScreen,
                        )),
                    Expanded(
                      flex: 9,
                      child: Container(
                        margin: _pageStyles.mainContainerPageEdgeInsets(),
                        child: Column(
                          children: [
                            Stack(
                              alignment: Alignment.center,
                              children: [
                                Container(
                                  padding: EdgeInsets.all(30.0),
                                  decoration: BoxDecoration(
                                    color: Get.isDarkMode
                                        ? AppTheme.colors.darkTheme2
                                        : Colors.black.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(3.0),
                                  ),
                                ),
                                _pageStyles.buildTabBarWithContoller(
                                    tabNames, coreMaterialTabController),
                              ],
                            ),
                            Expanded(
                              flex: 9,
                              child: Container(
                                child: TabBarView(
                                  controller: coreMaterialTabController,
                                  children:
                                      _subPrograms[0].lowerProgram!.map((p) {
                                    return CoreMaterialBooksTabPage(
                                      programId: p.id,
                                    );
                                  }).toList(),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ))
        : Container();
  }
}
